package com.infrastructure.net;

import android.os.Handler;

import com.google.gson.Gson;
import com.infrastructure.utils.BaseUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by zyt on 16/6/14 11:36 .
 * Email : syy19930112@aliyun.com
 * Description:
 * <p>
 * 具体执行网络请求任务的类,继承{@link Runnable}接口.
 * </p>
 */
public class HttpRequest implements Runnable {

    private URLData urlData;
    private String url;
    private List<RequestParameter> parameter;
    private RequestCallback requestCallback;

    private OkHttpClient okHttpClient;
    private Request request;
    private okhttp3.Response response;
    private Call call;

    private Handler handler;

    public HttpRequest(final URLData data, final List<RequestParameter> params,
                       final RequestCallback callBack) {
        urlData = data;
        url = urlData.getUrl();
        this.parameter = params;
        requestCallback = callBack;

        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient();
        }

        handler = new Handler();
    }

    /**
     * 获取Call对象
     *
     * @return
     */
    public Call getCall() {
        return call;
    }

    @Override
    public void run() {
        try {
            if (urlData.getNetType().equals("get")) {
                // 添加参数
                final StringBuffer paramBuffer = new StringBuffer();
                if ((parameter != null) && (parameter.size() > 0)) {
                    for (final RequestParameter p : parameter) {
                        if (paramBuffer.length() == 0) {
                            paramBuffer.append(p.getName() + "="
                                    + BaseUtils.UrlEncodeUnicode(p.getValue()));
                        } else {
                            paramBuffer.append("&" + p.getName() + "="
                                    + BaseUtils.UrlEncodeUnicode(p.getValue()));
                        }
                    }

                    String newUrl = url + "?" + paramBuffer.toString();
                    request = new Request.Builder().url(newUrl).build();
                } else {
                    request = new Request.Builder().url(url).build();
                }
            } else if (urlData.getNetType().equals("post")) {
                FormBody.Builder builder = new FormBody.Builder();
                // 添加参数
                if ((parameter != null) && (parameter.size() > 0)) {
                    for (final RequestParameter p : parameter) {
                        builder.add(p.getName(), p.getValue());
                    }
                    RequestBody formBody = builder.build();
                    request = new Request.Builder().url(url).post(formBody).build();
                }
            } else {
                return;
            }


            call = okHttpClient.newCall(request);
            // 发送请求
            response = call.execute();
            // 设置回调函数
            if ((requestCallback != null)) {
                if (response.isSuccessful()) {
                    String strResponse = response.body().toString();
                    final Response responseInJson = new Gson().fromJson(strResponse, Response.class);
                    if (responseInJson.hasError()) {
                        handleNetworkError(responseInJson.getErrorMessage());
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                HttpRequest.this.requestCallback
                                        .onSuccess(responseInJson.getResult());
                            }
                        });
                    }
                } else {
                    //请求失败,输出Http status 信息
                    handleNetworkError(response.code() + "-" + response.message());
                }
            }
        } catch (final java.lang.IllegalArgumentException e) {
            handleNetworkError("网络异常");
        } catch (final UnsupportedEncodingException e) {
            handleNetworkError("网络异常");
        } catch (final IOException e) {
            handleNetworkError("网络异常");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 网络异常处理
     *
     * @param errorMsg
     */

    public void handleNetworkError(final String errorMsg) {
        if(requestCallback != null)
            handler.post(new Runnable() {
                @Override
                public void run() {
                    HttpRequest.this.requestCallback.onFail(errorMsg);
                }
            });
    }

    /**
     * 将字节流转换成字符串
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String inputStreamToString(final InputStream is)
            throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }
}
